package org.jgs1904.apachepoidemo.utils;

/**
 * @author: 默苍璃
 * @date: 2023-10-09 18:53
 */
public class ExcelColumnConverter {

    // 将列字母转为列数字
    public static int columnToNumber(String column) {
        int result = 0;
        for (int i = 0; i < column.length(); i++) {
            result *= 26;
            result += column.charAt(i) - 'A' + 1;
        }
        return result;
    }

    // 将列数字转为列字母
    public static String numberToColumn(int number) {
        StringBuilder column = new StringBuilder();
        while (number > 0) {
            int rem = number % 26;
            if (rem == 0) {
                column.append('Z');
                number = (number / 26) - 1;
            } else {
                column.append((char) ((rem - 1) + 'A'));
                number /= 26;
            }
        }
        return column.reverse().toString();
    }

    public static void main(String[] args) {
        // 测试
        String columnLetter = "B";
        int columnNumber = 1;

        int convertedNumber = columnToNumber(columnLetter);
        String convertedLetter = numberToColumn(columnNumber);

        System.out.println(columnLetter + " 转换为数字: " + convertedNumber);
        System.out.println(columnNumber + " 转换为字母: " + convertedLetter);
    }
    
}